package com.sunny.gateway.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.sunny.gateway.dto.Menu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Properties;


@Slf4j
@Component
public class MenuPermissionLoader extends Subscriber<InstancesChangeEvent> {


	@Autowired
	DiscoveryClient discoveryClient;

	public  static HashMap<String, Menu> menuData = new HashMap<>();

	@Value("${spring.application.name}")
	private String applicationName;
	private String serverAddr;
	private String userName;
	private String passWord;
	@Value("${spring.cloud.nacos.config.namespace:public}")
	private String namespace;
	@Value("${spring.cloud.nacos.config.group:DEFAULT_GROUP}")
	private String defaultGroup;
	@Autowired
	private ConfigurableApplicationContext applicationContext;
	@Override
	public void onEvent(InstancesChangeEvent event) {
		discoveryClient.getServices().forEach(this::load);
	}

	private void load(String serviceId) {
		this.serverAddr = this.applicationContext.getEnvironment().getProperty("spring.cloud.nacos.config.server-addr");
		this.defaultGroup = this.applicationContext.getEnvironment().getProperty("spring.cloud.nacos.config.group");
		this.userName = this.applicationContext.getEnvironment().getProperty("spring.cloud.nacos.username");
		this.passWord = this.applicationContext.getEnvironment().getProperty("spring.cloud.nacos.password");
		this.initMenu(serviceId);
	}

	private void initMenu(String serviceId) {
		String content = null;
		ConfigService configService = null;
		try {
			Properties properties = new Properties();
			properties.put("serverAddr", this.serverAddr);
			properties.put("namespace", this.namespace);
			properties.put("username", this.userName);
			properties.put("password", this.passWord);
			configService = NacosFactory.createConfigService(properties);
			String dataId = serviceId + "_menu";
			content = configService.getConfig(dataId, this.defaultGroup, 5000L);

			if (org.springframework.util.StringUtils.isEmpty(content)) {
				log.warn("配置内容为空,跳过初始化!dataId:{}", dataId);
				return;
			}
			log.info("初始化菜单权限配置 !配置内容: dataId {} :{}",dataId, content);
			saveMenuData(serviceId,content);
		} catch (NacosException e) {
			throw new RuntimeException(e);
		}

	}

	private void saveMenuData(String dataId,String content) {
		menuData.put(dataId, JSON.parseObject(content,Menu.class));
	}

	/**
	 * 订阅类型方法，返回订阅的事件类型
	 * @return 订阅的事件类型
	 */
	@Override
	public Class<? extends Event> subscribeType() {
		return InstancesChangeEvent.class;
	}
}


